<template>
  <div>
    <el-dialog v-model="visible" title="新建待办" destroy-on-close :close-on-click-modal="false"
      :close-on-press-escape="false" @close="closeDialog" width="500">
      <el-form ref="formRef" :rules="rules" :model="formData.form" label-width="93px" style="margin-left: 30px;">
        <el-form-item required label="待办标题：" prop="title" style="width: 420px;">
          <el-input v-model="formData.form.title" />
        </el-form-item>
        <el-form-item required label="待办内容：" prop="content" style="width: 420px;">
          <el-input v-model="formData.form.content" />
        </el-form-item>
        <el-form-item required label="发送给：" prop="receiver" style="width: 420px;">
          <el-select v-model="formData.form.receiver" multiple placeholder="" popper-class="custom-header"
            placement="bottom" style="width: 420px;">
            <template #header>
              <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
                全选
              </el-checkbox>
            </template>
            <el-option v-for="item in optionuser" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item required label="截止时间：" prop="deadlineTime" style="width: 420px;">
          <el-date-picker v-model="formData.form.deadlineTime" style="width: 420px;" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder=" " />
        </el-form-item>
        <el-form-item required label="上传附件：" prop="files" style="width: 420px;">
          <UploadImgs :is-show-tip="true" v-model="formData.form.files" :limit="5" height="80px" width="80px"
            @onsuccess="onsuccess" @updatevalue="updatevalue" @alllist="alllist" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog" class="btnhover"
            style="width: 80px;height: 30px;background-color: rgba(255, 255, 255, 1);border: 1px solid rgba(187, 187, 187, 1);color: rgba(142, 142, 142, 1);">取消</el-button>
          <el-button type="primary" @click="besurebtn" style="width: 80px;height: 30px;">
            确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import * as getTodoApi from '@/api/todoCenter/index'
import UploadImgs from './UploadImgs.vue'
const formRef = ref() // 表单 Ref
const formData = reactive({
  form: {
    title: '',
    content: '',
    receiver: [],
    deadlineTime: '',
    files: '',
  }
})
const uploadData = ref([])
const props = defineProps({
  visible: Boolean,
  editData: {
    type: Object
  }
})

const checkAll = ref(false)
const indeterminate = ref(false)
const optionuser = ref([])
const rules = reactive({
  title: [{ required: true, message: '标题不能为空！', trigger: 'blur' }],
  content: [{ required: true, message: '内容不能为空！', trigger: 'blur' }],
  receiver: [{ required: true, message: '发送对象不能为空！', trigger: 'blur' }],
  deadlineTime: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('截止时间不能为空！'))
        } else {
          if (new Date(value).getTime() <= new Date().getTime()) {
            callback(new Error('待办截止时间必须是未来的时间！'))
          } else {
            callback()
          }
        }
      },
      trigger: 'change'
    }
  ],
  files: [{ required: true, message: '上传附件不能为空！', trigger: 'blur' }]
})
const emit = defineEmits(['update:visible', 'geteditData'])

const visible = computed({
  get: () => {
    return props.visible
  },
  set: (val) => emit('update:visible', val)
})
watch(() => props.editData, (val) => {
  if (val) {
    if (props.visible == true) {
      getUserList()
    }
  }
}, { immediate: true })
watch(formData.form.receiver, (val) => {
  if (val.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (val.length === optionuser.value.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
})

const handleCheckAll = (val) => {
  indeterminate.value = false
  if (val) {
    formData.form.receiver = optionuser.value.map((_) => _.value)
  } else {
    formData.form.receiver = []
  }
}
/** 取消 */
const closeDialog = () => {
  formRef.value.resetFields()
  formData.form.files = []
  uploadData.value = []
  visible.value = false
}
//上传成功
const onsuccess = (res) => {
  ElMessage.success('上传成功')
  uploadData.value.push(res.id)
}
//删除
const allList = ref([])
const fileList = ref([])
const newIds = ref([])
const updatevalue = (res) => {
  fileList.value = []
  fileList.value = res//删除后更新的图片
  newIds.value = []
  allList.value.forEach((item, index) => {
    fileList.value.find((item2) => {
      if (item === item2.url) {
        newIds.value.push(uploadData.value[index])
      }
    })
  })
  uploadData.value = newIds.value
}
//全部数据
const alllist = (res) => {
  allList.value = []
  allList.value = res
}

/** 确定 */
const besurebtn = async () => {
  formData.form.files = uploadData.value
  await formRef.value.validate()
  ElMessageBox.confirm(
    '是否确认新增待办?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const subitData = {
      title: formData.form.title,
      content: formData.form.content,
      receiver: formData.form.receiver.join(','),
      deadlineTime: formData.form.deadlineTime,
      files: formData.form.files
    }
    getTodoApi.createTodo(subitData).then((res) => {
      if (res) {
        ElMessage.success('新增成功！')
        emit('geteditData', props.editData.pageNo)
        formRef.value.resetFields()
        formData.form.files = []
        uploadData.value = []
        visible.value = false
      }
    })
  }).catch(() => {
    ElMessage.info('已取消新增待办')
  })
}

//获取用户
const getUserList = async () => {
  getTodoApi.getUserList().then((res) => {
    optionuser.value = []
    res.forEach((item) => {
      optionuser.value.push({
        label: item.nickname,
        value: item.id
      })
    })
  })
}

onMounted(() => {
})
</script>
<style scoped>
::v-deep .el-dialog__body {
  padding: 10px 0 !important;
}

::v-deep .upload .el-upload .el-upload-dragger {
  border: 1px solid var(--el-border-color-darker) !important;
}

::v-deep .upload .el-upload .el-upload-dragger:hover {
  border: 1.5px solid #ccc !important;
}

.btnhover:hover {
  opacity: 0.8;
}
</style>